package com.free4inno.knowledgems.controller;

import com.free4inno.knowledgems.dao.GroupInfoDAO;
import com.free4inno.knowledgems.dao.LabelInfoDAO;
import com.free4inno.knowledgems.dao.UserDAO;
import com.free4inno.knowledgems.domain.GroupInfo;
import com.free4inno.knowledgems.domain.LabelInfo;
import com.free4inno.knowledgems.domain.ResourceES;
import com.free4inno.knowledgems.domain.User;
import com.free4inno.knowledgems.service.LabelService;
import com.free4inno.knowledgems.service.ResourceEsService;
import com.free4inno.knowledgems.constants.UserConstants;
import com.free4inno.knowledgems.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.elasticsearch.client.transport.TransportClient;

import javax.servlet.http.HttpSession;

import java.util.*;

/**
 * SearchController.
 */

@Slf4j
@Controller
@RequestMapping("search")
public class SearchController {

    @Autowired
    private UserDAO userDao;

    @Autowired
    private GroupInfoDAO groupInfoDao;

    @Autowired
    private LabelInfoDAO labelInfoDao;

    @Autowired
    private LabelService labelService;

    @Autowired
    private ResourceEsService esService;

    @Autowired
    private SearchService searchService;

    private static TransportClient client;

    //跳转搜索结果页面
    @RequestMapping("searchAll")
    public String searchAll(@RequestParam("queryStr") String queryStr,
                            @RequestParam("groupIds") String groupIds,
                            @RequestParam("labelIds") String labelIds,
                            @RequestParam("times") int times,
                            Map param, HttpSession session) {
        log.info(this.getClass().getName() + "----in----" + "搜索资源(searchAll)" + "----" + session.getAttribute(UserConstants.USER_ID));
        param.put("queryStr", queryStr);
        param.put("groupIds", groupIds);
        param.put("labelIds", labelIds);
        param.put("times", times);
        log.info(this.getClass().getName() + "----out----" + "跳转搜索结果页面" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "search/searchresult";
    }

    //异步传输搜索结果列表
    @RequestMapping("searchdata")
    public String searchdata(@RequestParam("queryStr") String queryStr,
                             @RequestParam("page") int page,
                             @RequestParam("groupIds") ArrayList<String> groupIds,
                             @RequestParam("labelIds") ArrayList<String> labelIds,
                             @RequestParam("searchTimes") int searchTimes,
                             Map param, HttpSession session) {


        log.info(this.getClass().getName() + "----in----" + "异步传输搜索结果列表(searchdata)" + "----" + session.getAttribute(UserConstants.USER_ID));

        //取搜索条件中分类的name、uplevelid、id等信息
        log.info(this.getClass().getName() + "----" + "取搜索条件中分类的name、uplevelid、id等信息" + "----" + session.getAttribute(UserConstants.USER_ID));
        ArrayList<ArrayList<Map<String, Object>>> searchLabelInfos = labelService.switchLabelInfos(labelIds);

        //取搜索条件中“群组”的name
        log.info(this.getClass().getName() + "----" + "取搜索条件中“群组”的name" + "----" + session.getAttribute(UserConstants.USER_ID));
        String searchGroupNames = "";
        for (int i = 0; i < groupIds.size(); i++) {
            int id = Integer.parseInt(groupIds.get(i));
            GroupInfo groupInfo = groupInfoDao.findById(id).orElse(new GroupInfo());
            if (groupInfo.getGroupName() != null) {
                String gn = groupInfo.getGroupName();
                searchGroupNames = searchGroupNames + "," + gn;
            } else {
                searchGroupNames = searchGroupNames + "," + "未知群组" + id;
            }
        }
        if (!searchGroupNames.equals("")) {
            searchGroupNames = searchGroupNames.substring(1);
        }

        //判断登录状态
        log.info(this.getClass().getName() + "----" + "判断登录状态" + "----" + session.getAttribute(UserConstants.USER_ID));
        Boolean login = true;
        if (session == null || session.getAttribute(UserConstants.ACCOUNT) == null) {
            login = false; //未登录
            log.info(this.getClass().getName() + "----" + "未登录用户" + "----");
        } else {
            log.info(this.getClass().getName() + "----" + "已登录用户" + "----" + session.getAttribute(UserConstants.USER_ID));
        }

        /*
        System.out.println("groupIds");
        System.out.println(groupIds);
        System.out.println("searchGroupNames");
        System.out.println(searchGroupNames);
        System.out.println("page");
        System.out.println(page);
        System.out.println("size");
        System.out.println(size);
        System.out.println("queryStr");
        System.out.println(queryStr);
        System.out.println("labelIds");
        System.out.println(labelIds);
        System.out.println("labelInfos");
        System.out.println(searchLabelInfos);
        System.out.println("searchTimes");
        System.out.println(searchTimes);
        System.out.println("session");
        System.out.println(session.getAttribute(UserConstants.USER_ID).toString());

         */
        String userId = "0";    // 建议写为静态变量，暂时放在这里
        Object userIdObj = session.getAttribute(UserConstants.USER_ID);
        if(userIdObj != null) userId = userIdObj.toString();

        //ES搜索
        log.info(this.getClass().getName() + "----" + "ES搜索" + "----" + userId);
        int size = 10;
        Page<ResourceES> resourceESPage = esService.searchResourceES(page, size, queryStr, groupIds, labelIds, searchTimes, login, userId);

        //取pageSize
        long recordNum = resourceESPage.getTotalElements();
        long pageSize;
        if (recordNum % size == 0) {
            pageSize = recordNum / size;
        } else {
            pageSize = recordNum / size + 1;
        }

        //遍历搜索结果获取搜索结果列表中展示的标题、正文、作者名、群组名、标签名等信息
        log.info(this.getClass().getName() + "----" + "遍历结果列表获取结果信息" + "----" + userId);
        List<ResourceES> resourceESList = resourceESPage.getContent();

        /*
        System.out.println(resourceESList.size());
        resourceESList.forEach(item -> {
            System.out.println(item.getTitle());
            System.out.println(item.getResourceId());
            System.out.println(item.getGroup_id());
            System.out.println(item.getGroup_name());
            System.out.println(item.getLabel_id());
            System.out.println(item.getPermissionId());
            System.out.println();
        });
        System.out.println();
         */

        resourceESList = searchService.buildResourceES(resourceESList);

        param.put("queryStr", queryStr);
        param.put("groupIds", groupIds);
        param.put("labelIds", labelIds);

        param.put("pageSize", pageSize);
        param.put("resourceESList", resourceESList);
        param.put("recordNum", recordNum);

        param.put("searchGroupNames", searchGroupNames);
        param.put("searchLabelInfos", searchLabelInfos);

        log.info(this.getClass().getName() + "----out----" + "资源搜索结束，返回搜索结果" + "----" + session.getAttribute(UserConstants.USER_ID));
        return "search/_result";
    }
}
